package com.sh.data.engine.util;

import cn.hutool.core.collection.CollUtil;
import org.apache.commons.collections.CollectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import static com.sh.data.engine.util.DateUtil.judgeConvertToTimestamp;

/**
 * @author tinglan.ys
 * @description 关系型数据库批量插入
 * @date 2023/5/22 15:50
 */
public class BatchSaveUtil {

    public static void executeBatchSave(
        Connection conn, String sql, int size, List<Object> params, String targetType)
        throws SQLException {
        PreparedStatement ps = conn.prepareStatement(sql);

        boolean flag = false;
        List<List<Object>> batchList = CollUtil.split(params, size);
        for (int i = 0; i < batchList.size(); i++) {
            List<Object> batchBlock = batchList.get(i);
            if (CollectionUtils.isEmpty(batchBlock)) {
                continue;
            }
            for (int index = 0; index < batchBlock.size(); index++) {
                Object param = batchBlock.get(index);

                if (param instanceof String) {
                    String v = (String) param;
                    if (v.startsWith("\"")) {
                        v = v.substring(1);
                    }
                    if (v.endsWith("\"")) {
                        v = v.substring(0, v.length() - 1);
                    }
                    if ("POSTGRESQL".equalsIgnoreCase(targetType) || "KINGBASE8".equalsIgnoreCase(targetType)) {
                        // 如果目标数据库是pg，那么验证是否字符串为日期格式:yyyy-MM-dd HH:mm:ss.SSS或者yyyy-MM-dd HH:mm:ss。如果是日期的话存入时间戳
                        // 如果不是pg，不作处理
                        long timestamp = judgeConvertToTimestamp(v);
                        if (timestamp == -1) {
                            ps.setString(index + 1, v);
                        } else {
                            ps.setTimestamp(index + 1, new java.sql.Timestamp(timestamp));
                        }
                    } else {
                        ps.setString(index + 1, v);
                    }
                } else if (param instanceof Long) {
                    ps.setLong(index + 1, (Long) param);
                } else if (param instanceof Integer) {
                    ps.setInt(index + 1, (Integer) param);
                } else {
                    ps.setString(index + 1, param.toString());
                }
            }
            ps.addBatch();
            flag = true;
            if (i % 20 == 0) {
                ps.executeBatch();
                ps.clearBatch();
                flag = false;
            }
        }
        if (flag) {
            ps.executeBatch();
            ps.clearBatch();
        }
    }
}
